import React, { PureComponent, Fragment } from 'react';
import { Icon, Input, Upload, Col, Select, Button, Form, notification } from 'antd';
import { connect } from 'dva';
import "./form.less"
import "../../Common.less"
class BeamLenCal extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            tdata: [{}],
            roadlist: [],
            assignType:157
        }
        this.selectRoad = this.selectRoad.bind(this)
        this.calculate = this.calculate.bind(this)
        this.addRow = this.addRow.bind(this)
        this.removeRow = this.removeRow.bind(this)
        this.validate = this.validate.bind(this)
        this.select=this.select.bind(this)
    }
    async selectRoad(e) {
        console.log(e)
    }
    addRow(e, index) {
        e.preventDefault();
        let { tdata } = this.state

        tdata.splice(index + 1, 0, { id: new Date().getTime() })
        this.setState({
            tdata: [...tdata]
        })
    }
    validate(str) {
        let reg = true;
        str=str.replace(/\uff0c/g, ",")
        str=str.replace(/\s/g, "")
        if (str.includes(",")) {
            let arr = str.split(",");
            const len = arr.length;
            for (let i = 0; i < len; i++) {
                let item = arr[i];
                try {
                    eval(item)
                } catch (error) {
                    reg = false
                }
            }
        } else {
            reg = typeof (str - 0) == "number" ? true : false
        }
        return reg;
    }
    removeRow(e, index) {
        e.preventDefault();

        let { tdata } = this.state
        if (tdata.length < 2) {
            notification.warn({ message: "至少保留一组数据!" })
            return;
        }
        tdata.splice(index, 1)
        this.setState({
            tdata: [...tdata]
        })
    }
    calculate() {
        const list = document.querySelectorAll(".tableBoxS .input")
        const len = list.length;
        const {form,calculateBeam}=this.props;
        let arr = [];
        let obj = {};
        const {assignType}=this.state
        const num=assignType==158?13:14
        for (let i = 0; i < len; i++) {
            if (i % num == 0) {
                obj = {}
            }
            let node = list[i];
            node.classList.remove("required")
            if (!node.disabled) {
                if (!node.value) {
                    node.classList.add("required")
                    node.focus()
                    notification.warn({ message: `请将字段填写完整!` })
                    return;
                }
                if (node.dataset.validate) {
                    if (!this[node.dataset.validate](node.value)) {
                        node.classList.add("required")
                        node.focus()
                        notification.warn({ message: `${node.dataset.name}字段格式不正确!` })
                        return;
                    }
                }
                obj[node.dataset.key] = node.value.replace(/\uff0c/g, ",")

                if (i % num == num-1) {
                    arr.push(obj)
                }
            }
        }
        if (!form.getFieldValue("road")) {
            notification.warn({ message: "请选择线路!" })
            return;
        }
        if (!form.getFieldValue("bridgeWidth")) {
            notification.warn({ message: "请输入桥宽!" })
            return;
        }
        const values=form.getFieldsValue()
        calculateBeam({ beams: arr,assignType:values.values, bridgeWidth:values.bridgeWidth, roadlineId:values.road}, res => {
            let data = res.data.data;
            if (data) {
                let { modalContext } = this.props;
                modalContext.updateModal({
                    visible: true,
                    footer:null,
                    title: "预制梁长计算(单位:mm)",
                    event: { code: "beamLenModal" },
                    extra: {
                        tdata: data
                    }
                })
            }
        }, err => {

        })
    }
    async componentDidMount() {
        const { project, dictlist,loadProjectRoads } = this.props;
        let data = await loadProjectRoads({ projectId: project.id })
        if (data) {
            this.setState({
                roadlist: data.res,
                assignTypes: dictlist.filter(item => item.dictType == "assign_type"),
            })
        }

    }
    select(e){
        this.setState({
            assignType:e
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const { roadlist, tdata, assignTypes,assignType } = this.state
        return (
            <div className="beamLenCal">
                <div>
                    <Col span="24">
                        <Form style={{ padding: "15px 15px" }}
                            layout="inline"
                            labelCol={{ span: 5 }}
                            wrapperCol={{ span: 19 }}

                        >
                            <Form.Item style={{ width: "240px" }} labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }} label='路线'>
                                {getFieldDecorator('road', {
                                    rules: [
                                        { required: true, message: '请选择路线' },
                                    ],
                                   
                                })(
                                    <Select onSelect={this.selectRoad} placeholder="请选择线路">
                                        {
                                            roadlist.map(item => {
                                                return (
                                                    <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                                )
                                            })
                                        }

                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item style={{ width: "200px", marginRight: "10px" }} labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }} label='桥宽(m)'>
                                {getFieldDecorator('bridgeWidth', {
                                    rules: [
                                        { required: true, message: '桥宽' }
                                    ],
                                })(
                                    <Input type="number" placeholder="桥宽"></Input>
                                )}
                            </Form.Item>
                            <Form.Item labelCol={{ span: 10 }}
                                wrapperCol={{ span: 14}} style={{ width: "160px", marginRight: "10px" }} label='布置方式'>
                                {getFieldDecorator('assignType', {
                                    rules: [
                                        { required: false, message: '布置方式' }
                                    ],
                                    initialValue:157
                                })(
                                    <Select onChange={this.select}>
                                        {
                                            assignTypes && assignTypes.length ? assignTypes.map(item => {
                                                return (
                                                    <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                                )
                                            }) : undefined
                                        }
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item style={{ marginRight: "10px" }}>
                                <Button onClick={this.calculate} type="primary">计算</Button>
                            </Form.Item>
                            <Form.Item style={{ marginRight: "10px" }}>
                                <Upload showUploadList={false} className="modelUpload">
                                    <Button type="primary" > <Icon type="upload" /> 模板上传</Button>
                                </Upload>
                            </Form.Item>
                            <Form.Item>  <Button type="primary"><Icon type="cloud-download" />模板下载</Button></Form.Item>


                        </Form>
                    </Col>
                </div>
                <div className="tableBoxS tcBox">
                    <table style={{ width: "calc(100% - 30px)", margin: "auto" }}>
                        <tbody>
                            <tr className="th">
                                <td>位置</td>
                                <td>起点桩号(m)</td>
                                <td>终点桩号(m)</td>
                                <td>{assignType==157?"主梁间距(cm)":"主梁间距(cm)"}</td>
                                {
                                    assignType==157?<td>主梁间距(径向)(cm)</td>:undefined
                                }

                                <td>左左悬臂定位(cm)</td>
                                <td>左右悬臂定位(cm)</td>
                                <td>右左悬臂定位(cm)</td>
                                <td>右右悬臂定位(cm)</td>
                                <td>悬臂分段长度(cm)</td>
                                <td>操作</td>
                            </tr>
                            {
                                tdata && tdata.length ? tdata.map((item, index) => {
                                    return <Fragment key={'f' + index}>
                                        <tr>
                                            <td rowSpan="3"><textarea defaultValue="" className="input" data-key="position"  /></td>
                                            <td><input defaultValue="582.180" className="input" data-key="startStation" type="number" /></td>
                                            <td><input defaultValue="612.180" className="input" data-key="endStation" type="number" /></td>
                                            <td rowSpan="3"><textarea data-name="起点主梁间距" data-validate="validate" defaultValue="-300,-400,-500,300,400,500" className="input" data-key="startBeamSpacing"></textarea></td>
                                            {
                                                assignType==157? <td rowSpan="3"><textarea data-name="终点主梁间距" data-validate="validate" defaultValue="-300,-400,-500,300,400,500" className="input" data-key="endBeamSpacing"></textarea></td>:undefined
                                            }
                                           
                                            <td rowSpan="3"><textarea defaultValue="1500" className="input" data-key="llCantilever"></textarea></td>
                                            <td rowSpan="3"><textarea defaultValue="300" className="input" data-key="lrCantilever"></textarea></td>
                                            <td rowSpan="3"><textarea defaultValue="300" className="input" data-key="rlCantilever"></textarea></td>
                                            <td rowSpan="3"><textarea defaultValue="1500" className="input" data-key="rrCantilever"></textarea></td>
                                            <td rowSpan="3"><textarea defaultValue="250" className="input" data-key="singleLen"></textarea></td>
                                            <td rowSpan="3"><Icon onClick={e => this.addRow(e, index)} type="plus-square" /><Icon onClick={e => this.removeRow(e, index)} type="minus-square" /></td>
                                        </tr>
                                        <tr>
                                            <td><input className="input" defaultValue="90" data-key="startAngle" type="number" /></td>
                                            <td><input className="input" defaultValue="90" data-key="endAngle" type="number" /></td>
                                        </tr>
                                        <tr>
                                            <td><input className="input" defaultValue="8" data-key="leftDistance" type="number" /></td>
                                            <td><input className="input" defaultValue="8" data-key="rightDistance" type="number" /></td>
                                        </tr>
                                    </Fragment>
                                }) : undefined

                            }


                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
}

export default connect(
    ({
        project: { current },
        dict: { dictlist }
    }) => {
        return { project: current, dictlist };
    },
    dispatch => ({
        loadProjectRoads: (values) => dispatch({
            type: 'refRoads/loadProjectRoads',
            payload: values
        }),
        calculateBeam: (values, onSuccess, onError) => dispatch({
            type: 'calculate/calculateBeam',
            payload: {
                values,
                onSuccess,
                onError

            }
        })

    })
)(Form.create('BeamLenCal', {

})(BeamLenCal));